import base64
import json
import pickle

from django.http import JsonResponse, HttpResponseBadRequest
from django.views import View
from django_redis import get_redis_connection

from apps.goods.models import SKU


class CartsView(View):

    def post(self, request):
        # 接受数据
        json_date = json.loads(request.body)
        sku_id = json_date.get('sku_id')
        count = json_date.get('count')
        # 验证数据
        try:
            sku = SKU.objects.get(id=sku_id)
        except Exception as e:
            print(e)
            return JsonResponse({'code': 400, 'errmsg': '商品不存在'})
        try:
            count = int(count)
        except Exception as e:
            print(e)
            return JsonResponse({'code': 400, 'errmsg': '数量错误'})
        # 判断用户是否登录 没有登录就是AnonymouseUser对象
        user = request.user
        if user.is_authenticated:
            # 如果用户登录 保存到redis
            # 连接redis
            redis_conn = get_redis_connection('carts')
            pl = redis_conn.pipeline()
            # 操作hash
            pl.hincrby('cart_%s' % user.id, sku_id, count)
            # 操作set
            pl.sadd('selected_%s' % user.id, sku_id)
            pl.execute()
            # 返回响应
            return JsonResponse({'code': 0, 'errmsg': 'ok'})
        else:
            # 如果用户未登录 保存到cookie
            # 获取cookie数据
            cart_cookie = request.COOKIES.get('cart')
            # 保存
            if cart_cookie:
                carts = pickle.loads(base64.b64decode(cart_cookie))
            else:
                carts = {}
            # 生成字典数据
            if sku_id in carts:
                # 购物车 已经有sku_id对应的商品了 做数量的累加
                count_ori = carts[sku_id]['count'] # 取出原来的数量
                count += count_ori
            # 把数据添加到字典中
            carts[sku_id] = {
                'count': count,
                'selected': True,
            }
            # 字典转bytes
            carts_bytes = pickle.dumps(carts)
            # bytes转base64 转完后b64carts也是bytes类型
            b64carts = base64.b64encode(carts_bytes)
            # 添加cookie
            respone = JsonResponse({'code': 0, 'errmsg': 'ok'})
            # b64carts.decode()把二进制转为字符串 保存

            respone.set_cookie('cart', b64carts.decode(), max_age=3600*24*10)
            # 返回响应
            return respone

    def get(self, request):
        # 判断用户是否登录
        user = request.user
        if user.is_authenticated:
            # 登录用户去redis查询
            # 连接redis
            redis_conn = get_redis_connection('carts')
            # hash
            skuid_count = redis_conn.hgetall('cart_%s' % user.id)
            # set
            selected_skuids = redis_conn.smembers('selected_%s' % user.id)
            carts = {}
            # 把查询的数据构造成个cookie里的数据一样的格式
            for sku_id, count in skuid_count.items():
                carts[int(sku_id)] = {
                    'count': int(count),
                    'selected': sku_id in selected_skuids
                }


        else:
            # 未登录用户去cookie查询
            # 读取cookie数据
            cart_cookie = request.COOKIES.get("cart")
            # 保存
            if cart_cookie:
                carts = pickle.loads(base64.b64decode(cart_cookie))
            else:
                carts = {}

        # 根据商品id查商品信息
        # 遍历所有商品id
        sku_ids = carts.keys()
        # 查询所有的商品
        skus = SKU.objects.filter(id__in=sku_ids)

        # 把数据转为字典
        sku_list = []
        for sku in skus:
            sku_list.append({
                'id': sku.id,
                'name': sku.name,
                'price': sku.price,
                'default_image_url': sku.default_image.url,
                'count': carts[sku.id]['count'],
                'selected': carts[sku.id]['selected'],
            })

        # 返回响应
        return JsonResponse({'code': 0,'errmsg': 'ok', 'cart_skus': sku_list})

    def put(self, request):
        """修改购物车数据"""
        # 获取用户user
        user = request.user
        # 接受数据
        json_data = json.loads(request.body)
        sku_id = json_data.get('sku_id')
        count = json_data.get('count')
        selected = json_data.get('selected')
        # 验证数据
        if not all([sku_id, count, selected]):
            return JsonResponse({'code': 400, 'errmsg': '数据不全'})
        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return HttpResponseBadRequest('商品sku_id不存在')
        # 判断count是否为数字
        try:
            conut = int(count)
        except Exception:
            return HttpResponseBadRequest('参数count有误')
        if user.is_authenticated:
            # 登录后 修改redis
            # 链接redis
            redis_conn = get_redis_connection('carts')
            # hash
            redis_conn.hset('cart_%s' % user.id, sku_id, count)
            # set 无序无重复的集合
            if selected:
                redis_conn.sadd('selected_%s' % user.id, sku_id)
            else:
                redis_conn.srem('selected_%s' % user.id, sku_id)

            cart_sku = {'count': count, 'selected': selected, 'sku_id': sku_id}

            # 返回响应
            return JsonResponse({'code': 0, 'errmsg': 'ok', 'cart_sku': cart_sku})
        else:
            # 未登录
            # 修改cookie
            # 获取cookie数据
            cart_cookie = request.COOKIES.get('cart')
            # 数据解码
            carts = pickle.loads(base64.b64decode(cart_cookie))
            # 更新数据
            carts[sku_id]['count'] = count
            carts[sku_id]['selected'] = selected
            # 编码
            # 字典转bytes
            carts_bytes = pickle.dumps(carts)
            # bytes转base64 转为后b64carts也是bytes类型
            b64carts = base64.b64encode(carts_bytes)
            # 返回响应
            cart_sku = {'count': count, 'selected': selected, 'sku_id': sku_id}
            # 添加cookie
            response = JsonResponse({'code': 0, 'errmsg': 'ok', 'cart_sku': cart_sku})
            # b64carts.decode()将二进制转为字符串 保存
            response.set_cookie('cart', b64carts.decode(), max_age=3600*24*10)
            # 返回响应
            return response

    def delete(self, request):
        # 获取用户user
        user = request.user
        # 接受数据
        json_data = json.loads(request.body)
        sku_id = json_data.get('sku_id')
        # 验证数据
        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return HttpResponseBadRequest('商品sku_id不存在')
        if user.is_authenticated:
            # 登录后redis里删除链接redis
            redis_conn = get_redis_connection('carts')
            # del
            redis_conn.hdel('cart_%s' % user.id, sku_id)
            # rem
            redis_conn.srem('selected_%s' % user.id, sku_id)
            # 返回响应
            return JsonResponse({'code': 0, 'errmsg': 'ok'})
        else:
            # 未登录
            # cookie里删除
            cart_cookie = request.COOKIES.get('cart')
            # 数据解码
            carts = pickle.loads(base64.b64decode(cart_cookie))
            # 更新数据
            del carts[sku_id]
            # 字典转bytes
            cart_bytes = pickle.dumps(carts)
            # bytes转base64 转完后b64carts也是bytes类型
            b64carts = base64.b64encode(cart_bytes)
            response = JsonResponse({'code': 0, 'errmsg': 'ok'})
            # b64carts.decode()把二进制为字符串 保存
            response.set_cookie('cart', b64carts.decode(), max_age=3600*24*10)
            # 返回响应
            return response

class CartsSelectAllView(View):
    """全选购物车"""

    def put(self, request):
        # 接收和校验参数
        json_dict = json.loads(request.body.decode())
        selected = json_dict.get('selected', True)

        # 校验参数
        if selected:
            if not isinstance(selected, bool):
                return HttpResponseBadRequest('参数selected有误')

        # 判断用户是否登录
        user = request.user
        if user is not None and user.is_authenticated:
            # 用户已登录，操作redis购物车
            redis_conn = get_redis_connection('carts')
            cart = redis_conn.hgetall('cart_%s' % user.id)
            sku_id_list = cart.keys()
            if selected:
                # 全选
                redis_conn.sadd('selected_%s' % user.id, *sku_id_list)
            else:
                redis_conn.srem('selected_%s' % user.id, *sku_id_list)
            return JsonResponse({'code': 0, 'errmsg': '全选购物车成功'})
        else:
            # 用户已登录，操作cookie购物车
            cart = request.COOKIES.get('cart')
            response = JsonResponse({'code': 0, 'errmsg': '全选购物车成功'})
            if cart is not None:
                cart = pickle.loads(base64.b64decode(cart.encode()))
                for sku_id in cart:
                    cart[sku_id]['selected'] = selected
                cookie_cart = base64.b64encode(pickle.dumps(cart)).decode()
                response.set_cookie('cart', cookie_cart, max_age=7*24*3600)

            return response

class CartSimpleView(View):
    """商品页面右上角购物车"""

    def get(self, request):
        # 判断用户是否登录
        user = request.user
        if user.is_authenticated:
            # 用户已登录，查询redis购物车
            redis_conn = get_redis_connection('carts')
            print(redis_conn, '\n-------------------------------------------')
            redis_cart = redis_conn.hgetall('cart_%s' % user.id)
            print(redis_cart, '\n-------------------------------------------')
            cart_selected = redis_conn.smembers('selected_%s' % user.id)
            # 将redis中的俩个数据统一格式，跟cookie中的格式一致，方便统一查询
            cart_dict = {}
            for sku_id, count in redis_cart.items():
                cart_dict[int(sku_id)] = {
                    'count': int(count),
                    'selected': sku_id in cart_selected
                }
        else:
            # 用户未登录，查询cookie购物车
            cart_str = request.COOKIES.get('carts')
            if cart_str:
                cart_dict = pickle.loads(base64.b64decode(cart_str.encode()))
            else:
                cart_dict = {}

        # 构造简单购物车json数据
        cart_skus = []
        sku_ids = cart_dict.keys()
        skus = SKU.objects.filter(id__in=sku_ids)
        for sku in skus:
            cart_skus.append({
                'id': sku.id,
                'name': sku.name,
                'count': cart_dict.get(sku.id).get('count'),
                'default_image_url': sku.default_image.url,
            })

        # 响应json列表数据
        return JsonResponse({'code': 0, 'errmsg': 'ok', 'cart_skus': cart_skus})
